//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Web;
using CommunityServer.Files.Components;
using CommunityServer.Components;
using CommunityServer.Files;

namespace CommunityServer.ControlPanel.UI
{
	/// <summary>
	/// Summary description for BaseBlogPage.
	/// </summary>
	public class BaseFilesPage : PanelPage
	{
		public BaseFilesPage()
		{
		}

		protected override void Authorize()
		{
			base.Authorize ();

			Folder f = FolderLookUp();
			if (f != null)
				Permissions.AccessCheck(f,Permission.Administer,CSContext.Current.User);

			SetLocation();
		}

		public void SetCookie(Folder f)
		{
			if(f == null)
				return;

			CSContext context = CSContext.Current;
			HttpCookie cookie = context.Context.Request.Cookies[CreateApplicationCookieName(context,"files")];
			if(cookie == null)
			{
				cookie = new HttpCookie(CreateApplicationCookieName(context,"files")); 
                
			}

			cookie.Values["FolderID"] = f.SectionID.ToString();
			cookie.Expires = DateTime.Now.AddDays(30);

			context.Context.Response.Cookies.Add(cookie);
            
		}

		protected virtual Folder FolderLookUp()
		{
			if(_folder == null)
			{
				CSContext context = CSContext.Current;

				if(context.SectionID > 0)
				{
					_folder = Folders.GetFolder(context.SectionID,true);
					SetCookie(_folder);
				}
				else if(!Globals.IsNullorEmpty(context.ApplicationKey))
				{
					_folder = Folders.GetFolder(context.ApplicationKey,true);
					SetCookie(_folder);
				}
				else
				{
					HttpCookie cookie = context.Context.Request.Cookies[CreateApplicationCookieName(context,"files")];
					if(cookie != null)
					{
						if(!Globals.IsNullorEmpty(cookie.Values["FolderID"]))
						{
							int fid = Int32.Parse(cookie.Values["FolderID"]);
							try
							{
								_folder = Folders.GetFolder(fid,true);
							}
							catch{}
						}
					}
				}
						
				if(_folder == null)
				{
					ArrayList folders = Folders.GetFolders(true,false);
					folders = Sections.FilterByAccessControl(folders,Permission.Administer,context.User);

					if(folders != null && folders.Count == 1)
					{
						_folder = folders[0] as Folder;
						SetCookie(_folder);
					}
				}

				if(_folder == null)
					Response.Redirect("switch.aspx");
			}

			return _folder;
		}

		private Folder _folder = null;
		public Folder CurrentFolder
		{
			get{ return _folder;}
		}
	}
}
